package com.xuelang.pipeline.app.resource.util;

import com.xuelang.hiforce.base.utils.http.SSLSocketClient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.xuelang.hiforce.base.utils.http.OkHttpUtil.JSON;

/**
 * @author liuyuan.ly
 * @since 2024/8/22 17:40
 */
@Slf4j
public class HttpUtil {

    public static OkHttpClient getClient() {
        return new OkHttpClient().newBuilder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .build();
    }

    /**
     * 同步post方式请求-json提交参数
     */
    public static String doPost(String url, final String json) throws IOException {
        OkHttpClient client = getClient();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }

    }
}
